package com.lyl.lawyer.controller;

import com.cn.lyl.lawyer.model.entity.UserModel;
import com.cn.lyl.lawyer.service.UserService;
import com.cn.lyl.lawyer.util.CommonResult;
import com.cn.lyl.lawyer.util.DrawCode;
import com.cn.lyl.lawyer.util.Upload;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import java.util.UUID;


@RestController

public class CommonController {

    @Value("${path.realPath}")
    private String realPath;
    @Value("${path.targetPath}")
    private String targetPath;
    @Value("${path.webPath}")
    private String webPath;
    @Autowired
    private UserService userService;
    @PostMapping("/login")
    public Object login(HttpSession session, UserModel userModel, ModelMap model){
        System.out.println(session.getAttribute("code"));
        userModel.setCode((String) session.getAttribute("code"));
        String result = userService.checkLogin(userModel);
        if(result.equals("success")){
            session.setAttribute(userModel.getUsername(),userModel.getUsername());
        }
        return CommonResult.success(result);
    }

    @GetMapping("/code")
    public void code(HttpSession session, HttpServletResponse resp) throws IOException {
        BufferedImage image = new BufferedImage(80, 30, BufferedImage.TYPE_INT_RGB);
        //1.获取图片画笔
        Graphics g = image.getGraphics();
        Random r = new Random();//随机数
//        r.nextInt(255)，随机数在0到255之间 而且必须是整数 0-1之间的小数
        //2.设置画笔颜色
//        设置背景颜色，RGB 三个参数
        g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
        //3. .绘制矩形的背景
        g.fillRect(0, 0, 80, 30);
        //4.调用自定义的方法,获取长度为5的字母数字组合的字符串
        String number = DrawCode.getNumber(5);
        System.out.println(number);
      //就是为了判断登录时的验证码是否正确
     //   model.addAttribute("Code", number);
        session.setAttribute("code",number);
        g.setColor(new Color(0, 0, 0));
        g.setFont(new Font("宋体", Font.BOLD, 24));
        //5.设置颜色字体后，绘制字符串
        g.drawString(number, 5, 25);
        //6.绘制18条干扰线
        for (int i = 0; i < 18; i++) {

            g.setColor(new
                    Color(r.nextInt(255), r.nextInt(255), r.nextInt(255), r.nextInt(255)));

            g.drawLine(r.nextInt(100),
                    r.nextInt(30),
                    r.nextInt(100),
                    r.nextInt(30));
//            直线参数 （a,b,x,y),a,b代表起点，x，y代表终点
        }
        resp.setContentType("image/jpeg");
        OutputStream ops = resp.getOutputStream();
        ImageIO.write(image, "jpeg", ops);
        ops.close();
    }

    @PostMapping("/upload")
    public Object upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String extension = FilenameUtils.getExtension(originalFilename);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String newName = uuid+"."+extension;
        File destRealFile = new File(realPath,newName);

        Upload.copy(file,targetPath,newName);
        Upload.copy(file,webPath,newName);

        if (!destRealFile.getParentFile().exists()) {
            destRealFile.getParentFile().mkdirs();
        }
        file.transferTo(destRealFile);

        return CommonResult.success("/img/"+newName);


    }

    @ResponseBody
    @GetMapping("/notLogin")
    public Object notLogin(){
        return CommonResult.unauthorized(null);
    }
}
